package jehc.djshi.web.config;
import jehc.djshi.oauth.client.AuthHandler;
import jehc.djshi.common.util.logger.Logback4jUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;

/**
 * @Desc
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Configuration
public class ConfigBean  extends Logback4jUtil implements WebMvcConfigurer {
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    /**
     * 由于在拦截器中注解无效，需要提前注入bean
     * @return
     */
    @Bean
    public AuthHandler authHandler(){
        return new AuthHandler();
    }

    /**
     * 跨域配置
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // 允许跨域的头部信息
        config.addAllowedHeader("*");
        // 允许跨域的方法
        config.addAllowedMethod("*");
        // 可访问的外部域
        config.addAllowedOrigin("*");
        // 需要跨域用户凭证（cookie、HTTP认证及客户端SSL证明等）
        //config.setAllowCredentials(true);
        //config.addAllowedOriginPattern("*");
        // 跨域路径配置
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    /**
     * 放开资源
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(authHandler());
        registration.addPathPatterns("/**");
        registration.excludePathPatterns(
                "/favicon.ico",
                "/js/**",
                "/html/**",
                "/resources/*",
                "/webjars/**",
                "/v2/api-docs/**",
                "/swagger-ui.html/**",
                "/swagger-resources/**",
                "/oauth",
                "/druid/**",
                "/druid",
                "/monitor/druid",
                "/isAdmin",
                "/accountInfo",
                "/httpSessionEntity"
        );
    }
}
